import text from "./fields/TextField.vue"
import checkbox from "./fields/CheckBoxField.vue"
import mtext from "./fields/MTextField.vue"
import radios from "./fields/RadioGroupField.vue"
import EnumCheckBoxes from "./fields/EnumCheckBoxes.vue"
import select from "./fields/EnumSelect.vue"
import radio from "./fields/EnumRadioBox.vue"
import SwitchBoxField from "./fields/SwitchBoxField.vue"
import date from "./fields/DateField.vue"



const field_defs = {
  text, checkbox, mtext, radios, select, radio, date,
  "switch": SwitchBoxField,
  "enum-checkbox": EnumCheckBoxes,
  "default": text
}

export function raw_value(meta, model) {
  const attr = meta.name;
  let modelData = model.data;
  return (modelData && modelData[attr])
}

export function fields(meta) {
  const { control } = meta;
  return ((control && field_defs[control]) || field_defs.default);
}

export function displayValue(meta, model) {
  let value = raw_value(meta, model);
  value = value || meta.defaultValue;
  return value == null ? "~" : value;
}

export function get(meta, model) {
  return raw_value(meta, model);
}

export function set(meta, model, newValue, raiseEvent) {
  const attr = meta.name;
  let modelData = model.data || {

  };
  let oldValue = modelData[attr];
  modelData[attr] = newValue;
  if (raiseEvent == null || raiseEvent == true) {
    // model.exec("valueChanged", {
    //   attr,
    //   "data": modelData,
    //   oldValue,
    //   newValue
    // });
  }
  model.data = modelData;
}

export function editMode(meta, model) {
  if (model.mode == "browse") {
    return false;
  } else {
    return meta.readonly == false;
  }
}

export default {
  fields, get, set, editMode, displayValue
}